import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;

import org.apache.commons.io.FileUtils;

import com.drew.imaging.ImageMetadataReader;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;
import com.drew.metadata.exif.ExifIFD0Descriptor;
import com.drew.metadata.exif.ExifIFD0Directory;
import com.drew.metadata.exif.ExifSubIFDDirectory;
import com.drew.metadata.exif.ExifThumbnailDirectory;

public class RawReader {

	public static void main(String[] args) throws Exception {
		// method();
		File file = new File("/home/nitish/Documents/NK_D70.NEF");
		Metadata metadata = ImageMetadataReader.readMetadata(file);
		Iterable<Directory> directories = metadata.getDirectories();
		for (Iterator iterator = directories.iterator(); iterator.hasNext();) {
			Directory type = (Directory) iterator.next();
			Collection<Tag> tags = type.getTags();
			for (Tag tag : tags) {
				System.out.println(type.getName() + "-" + tag.getTagName()
						+ ":" + type.getObject(tag.getTagType()));
			}
		}
		int compression = metadata.getDirectory(ExifIFD0Directory.class)
				.getInt(0x0103);
		int stripByteCounts = 0;
		int stripOffsets = 0;
		if (compression == 6) {
			stripOffsets = metadata.getDirectory(ExifIFD0Directory.class)
					.getInt(0x0111);
			System.out.println(stripOffsets);
			stripByteCounts = metadata.getDirectory(ExifIFD0Directory.class)
					.getInt(0x0117);
		} else if (compression == 1) {
			compression = metadata.getDirectory(ExifSubIFDDirectory.class)
					.getInt(0x0103);
			if (compression == 6) {
				stripOffsets = metadata.getDirectory(ExifSubIFDDirectory.class)
						.getInt(0x0111);
				System.out.println(stripOffsets);
				stripByteCounts = metadata.getDirectory(
						ExifSubIFDDirectory.class).getInt(0x0117);
			}
		}
		byte[] read = FileUtils.readFileToByteArray(file);
		byte[] b = new byte[stripByteCounts];
		System.arraycopy(read, stripOffsets, b, 0, stripByteCounts);
		FileUtils.writeByteArrayToFile(new File("/home/nitish/NK_D70.jpg"), b);
		byte[] thumbnailData = metadata.getDirectory(
				ExifThumbnailDirectory.class).getThumbnailData();
		FileUtils.writeByteArrayToFile(new File("/home/nitish/NK_D70_1.jpg"),
				thumbnailData);
	}

	private static void method() throws IOException {
		byte[] read = FileUtils.readFileToByteArray(new File(
				"/home/nitish/IMG_9129.CR2"));
		int len = 2132767;
		int offset = 59028;
		byte[] b = new byte[len + 3];
		System.arraycopy(read, offset, b, 0, len);
		// b[0] = (byte) 0xFF;
		// b[1] = (byte) 0xD8;
		// b[2] = (byte) 0xFF;
		FileUtils.writeByteArrayToFile(new File("/home/nitish/3.jpg"), b);
	}
}
